

#include "stdafx.h"
#include "pf_line.h"

#include "pf_debug.h"
#include "pf_graphicview.h"
#include "pf_painter.h"
#include "pf_graphic.h"

/**
 * Constructor.
 */
PF_Line::PF_Line(PF_Container* parent,
                 const PF_LineAttribute& d)
        :PF_AtomicEntity(parent), data(d) {
    calculateBorders();
}



/**
 * Destructor.
 */
PF_Line::~PF_Line() {}




PF_Entity* PF_Line::clone() {
    PF_Line* l = new PF_Line(*this);
    l->initId();
    return l;
}



void PF_Line::calculateBorders() {
    minV = PF_Vector::minimum(data.startpoint, data.endpoint);
    maxV = PF_Vector::maximum(data.startpoint, data.endpoint);
}



PF_VectorSolutions PF_Line::getRefPoints() {
	PF_VectorSolutions ret(data.startpoint, data.endpoint);
	return ret;
}


PF_Vector PF_Line::getNearestEndpoint(const PF_Vector& coord,
                                      double* dist) {
    double dist1, dist2;
    PF_Vector* nearerPoint;

    dist1 = data.startpoint.distanceTo(coord);
    dist2 = data.endpoint.distanceTo(coord);

    if (dist2<dist1) {
        if (dist!=NULL) {
            *dist = dist2;
        }
        nearerPoint = &data.endpoint;
    } else {
        if (dist!=NULL) {
            *dist = dist1;
        }
        nearerPoint = &data.startpoint;
    }

    return *nearerPoint;
}



PF_Vector PF_Line::getNearestPointOnEntity(const PF_Vector& coord,
        bool onEntity, double* dist, PF_Entity** entity) {

    if (entity!=NULL) {
        *entity = this;
    }

    PF_Vector ae = data.endpoint-data.startpoint;
    PF_Vector ea = data.startpoint-data.endpoint;
    PF_Vector ap = coord-data.startpoint;
    PF_Vector ep = coord-data.endpoint;

    if (ae.magnitude()<1.0e-6 || ea.magnitude()<1.0e-6) {
        if (dist!=NULL) {
            *dist = LX_DOUBLEMAX;
        }
        return PF_Vector(false);
    }

    // Orthogonal projection from both sides:
    PF_Vector ba = ae * PF_Vector::dotP(ae, ap)
                   / (ae.magnitude()*ae.magnitude());
    PF_Vector be = ea * PF_Vector::dotP(ea, ep)
                   / (ea.magnitude()*ea.magnitude());

    // Check if the projection is within this line:
    if (onEntity==true &&
            (ba.magnitude()>ae.magnitude() || be.magnitude()>ea.magnitude())) {
        return getNearestEndpoint(coord, dist);
    } else {
        if (dist!=NULL) {
            *dist = coord.distanceTo(data.startpoint+ba);
        }
        return data.startpoint+ba;
    }
}



PF_Vector PF_Line::getNearestCenter(const PF_Vector& coord,
                                    double* dist) {

    PF_Vector p = (data.startpoint + data.endpoint)/2.0;

    if (dist!=NULL) {
        *dist = p.distanceTo(coord);
    }

    return p;
}



PF_Vector PF_Line::getNearestMiddle(const PF_Vector& coord,
                                    double* dist) {
    return getNearestCenter(coord, dist);
}



PF_Vector PF_Line::getNearestDist(double distance,
                                  const PF_Vector& coord,
                                  double* dist) {

    double a1 = getAngle1();

    PF_Vector dv;
    dv.setPolar(distance, a1);

    PF_Vector p1 = data.startpoint + dv;
    PF_Vector p2 = data.endpoint - dv;

    double dist1, dist2;
    PF_Vector* nearerPoint;

    dist1 = p1.distanceTo(coord);
    dist2 = p2.distanceTo(coord);

    if (dist2<dist1) {
        if (dist!=NULL) {
            *dist = dist2;
        }
        nearerPoint = &p2;
    } else {
        if (dist!=NULL) {
            *dist = dist1;
        }
        nearerPoint = &p1;
    }

    return *nearerPoint;
}



PF_Vector PF_Line::getNearestDist(double distance,
                                  bool startp) {

    double a1 = getAngle1();

    PF_Vector dv;
    dv.setPolar(distance, a1);
	PF_Vector ret;

	if (startp) {
    	ret = data.startpoint + dv;
	}
	else {
    	ret = data.endpoint - dv;
	}

	return ret;

}


/*PF_Vector PF_Line::getNearestRef(const PF_Vector& coord,
                                 double* dist) {
    double d1, d2, d;
    PF_Vector p;
    PF_Vector p1 = getNearestEndpoint(coord, &d1);
    PF_Vector p2 = getNearestMiddle(coord, &d2);

    if (d1<d2) {
        d = d1;
        p = p1;
    } else {
        d = d2;
        p = p2;
    }

    if (dist!=NULL) {
        *dist = d;
    }

    return p;
}*/


double PF_Line::getDistanceToPoint(const PF_Vector& coord,
                                   PF_Entity** entity,
                                   LX_Define::ResolveLevel /*level*/,
								   double /*solidDist*/) {

    PF_DEBUG->print("PF_Line::getDistanceToPoint");

    if (entity!=NULL) {
        *entity = this;
    }
    // check endpoints first:
    double dist = coord.distanceTo(getStartpoint());
    if (dist<1.0e-4) {
        PF_DEBUG->print("PF_Line::getDistanceToPoint: OK1");
        return dist;
    }
    dist = coord.distanceTo(getEndpoint());
    if (dist<1.0e-4) {
        PF_DEBUG->print("PF_Line::getDistanceToPoint: OK2");
        return dist;
    }

    dist = LX_DOUBLEMAX;
    PF_Vector ae = data.endpoint-data.startpoint;
    PF_Vector ea = data.startpoint-data.endpoint;
    PF_Vector ap = coord-data.startpoint;
    PF_Vector ep = coord-data.endpoint;

    if (ae.magnitude()<1.0e-6 || ea.magnitude()<1.0e-6) {
        PF_DEBUG->print("PF_Line::getDistanceToPoint: OK2a");
        return dist;
    }

    // Orthogonal projection from both sides:
    PF_Vector ba = ae * PF_Vector::dotP(ae, ap) /
                   PF_Math::pow(ae.magnitude(), 2);
    PF_Vector be = ea * PF_Vector::dotP(ea, ep) /
                   PF_Math::pow(ea.magnitude(), 2);

    // Check if the projection is outside this line:
    if (ba.magnitude()>ae.magnitude() || be.magnitude()>ea.magnitude()) {
        // return distance to endpoint
        getNearestEndpoint(coord, &dist);
        PF_DEBUG->print("PF_Line::getDistanceToPoint: OK3");
        return dist;
    }
    //PF_DEBUG->print("ba: %f", ba.magnitude());
    //PF_DEBUG->print("ae: %f", ae.magnitude());

    PF_Vector cp = PF_Vector::crossP(ap, ae);
    dist = cp.magnitude() / ae.magnitude();

    PF_DEBUG->print("PF_Line::getDistanceToPoint: OK4");

    return dist;
}



void PF_Line::moveStartpoint(const PF_Vector& pos) {
    data.startpoint = pos;
    calculateBorders();
}



void PF_Line::moveEndpoint(const PF_Vector& pos) {
    data.endpoint = pos;
    calculateBorders();
}



LX_Define::Ending PF_Line::getTrimPoint(const PF_Vector& coord,
                                  const PF_Vector& trimPoint) {

    double angEl = getAngle1();
    double angM = trimPoint.angleTo(coord);
    double angDif = angEl-angM;

    if (angDif<0.0) {
        angDif*=-1.0;
    }
    if (angDif>M_PI) {
        angDif=2*M_PI-angDif;
    }

    if (angDif<M_PI/2.0) {
        return LX_Define::EndingStart;
    } else {
        return LX_Define::EndingEnd;
    }
}


void PF_Line::reverse() {
    PF_Vector v = data.startpoint;
    data.startpoint = data.endpoint;
    data.endpoint = v;
}



bool PF_Line::hasEndpointsWithinWindow(PF_Vector v1, PF_Vector v2) {
    if (data.startpoint.isInWindow(v1, v2) ||
            data.endpoint.isInWindow(v1, v2)) {
        return true;
    } else {
        return false;
    }
}


void PF_Line::move(PF_Vector offset) {
	PF_DEBUG->print("PF_Line::move1: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
		
	PF_DEBUG->print("PF_Line::move1: offset: %f/%f", offset.x, offset.y);
	
    data.startpoint.move(offset);
    data.endpoint.move(offset);
    calculateBorders();
	PF_DEBUG->print("PF_Line::move2: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
}



void PF_Line::rotate(PF_Vector center, double angle) {
	PF_DEBUG->print("PF_Line::rotate");
	PF_DEBUG->print("PF_Line::rotate1: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
    data.startpoint.rotate(center, angle);
    data.endpoint.rotate(center, angle);
	PF_DEBUG->print("PF_Line::rotate2: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
    calculateBorders();
	PF_DEBUG->print("PF_Line::rotate: OK");
}



void PF_Line::scale(PF_Vector center, PF_Vector factor) {
	PF_DEBUG->print("PF_Line::scale1: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
    data.startpoint.scale(center, factor);
    data.endpoint.scale(center, factor);
	PF_DEBUG->print("PF_Line::scale2: sp: %f/%f, ep: %f/%f", 
		data.startpoint.x, data.startpoint.y,
		data.endpoint.x, data.endpoint.y);
    calculateBorders();
}



void PF_Line::mirror(PF_Vector axisPoint1, PF_Vector axisPoint2) {
    data.startpoint.mirror(axisPoint1, axisPoint2);
    data.endpoint.mirror(axisPoint1, axisPoint2);
    calculateBorders();
}


/**
 * Stretches the given range of the entity by the given offset.
 */
void PF_Line::stretch(PF_Vector firstCorner,
                      PF_Vector secondCorner,
                      PF_Vector offset) {

    if (getStartpoint().isInWindow(firstCorner,
                                   secondCorner)) {
        moveStartpoint(getStartpoint() + offset);
    }
    if (getEndpoint().isInWindow(firstCorner,
                                 secondCorner)) {
        moveEndpoint(getEndpoint() + offset);
    }
}



void PF_Line::moveRef(const PF_Vector& ref, const PF_Vector& offset) {
    if (ref.distanceTo(data.startpoint)<1.0e-4) {
        moveStartpoint(data.startpoint+offset);
    }
    if (ref.distanceTo(data.endpoint)<1.0e-4) {
        moveEndpoint(data.endpoint+offset);
    }
}




void PF_Line::draw(PF_Painter* painter, PF_GraphicView* view, double patternOffset) {
    if (painter==NULL || view==NULL) {
        return;
    }

    if (getPen().getLineType()==LX_Define::SolidLine ||
            isSelected() ||
            view->getDrawingMode()==LX_Define::ModePreview) {

        painter->drawLine(view->toGui(getStartpoint()),
                          view->toGui(getEndpoint()));
    } else {
        double styleFactor = getStyleFactor(view);
		if (styleFactor<0.0) {
        	painter->drawLine(view->toGui(getStartpoint()),
                          view->toGui(getEndpoint()));
			return;
		}
		
        // Pattern:
        PF_LinePattern* pat;
        if (isSelected()) {
            pat = &patternSelected;
        } else {
            pat = view->getPattern(getPen().getLineType());
        }
        if (pat==NULL) {
            PF_DEBUG->print(PF_Debug::D_WARNING,
				"PF_Line::draw: Invalid line pattern");
            return;
        }

        // Pen to draw pattern is always solid:
        PF_Pen pen = painter->getPen();

        pen.setLineType(LX_Define::SolidLine);
        painter->setPen(pen);

		// index counter
        int i;

		// line data:
        double length = getLength();
        double angle = getAngle1();
		
		// pattern segment length:
		double patternSegmentLength = 0.0;

        // create pattern:
        PF_Vector* dp = new PF_Vector[pat->num];

        for (i=0; i<pat->num; ++i) {
            dp[i] = PF_Vector(cos(angle) * fabs(pat->pattern[i] * styleFactor),
                              sin(angle) * fabs(pat->pattern[i] * styleFactor));

			patternSegmentLength += fabs(pat->pattern[i] * styleFactor);
        }

		// handle pattern offset:
		int m;
		if (patternOffset<0.0) {
			m = (int)ceil(patternOffset / patternSegmentLength);
		}
		else {
			m = (int)floor(patternOffset / patternSegmentLength);
		}
		
		patternOffset -= (m*patternSegmentLength);
		//if (patternOffset<0.0) {
		//	patternOffset+=patternSegmentLength;
		//}
		//PF_DEBUG->print("pattern. offset: %f", patternOffset);
		PF_Vector patternOffsetVec;
		patternOffsetVec.setPolar(patternOffset, angle);
		
        double tot=patternOffset;
        i=0;
        bool done = false;
		bool cutStartpoint, cutEndpoint, drop;
        PF_Vector curP=getStartpoint()+patternOffsetVec;

        do {
			cutStartpoint = false;
			cutEndpoint = false;
			drop = false;
			
			// line segment (otherwise space segment)
            if (pat->pattern[i]>0.0) {
				// drop the whole pattern segment line:
				if (tot+pat->pattern[i]*styleFactor < 0.0) {
					drop = true;
				}
				else {
					// trim startpoint of pattern segment line to line startpoint
					if (tot < 0.0) {
						cutStartpoint = true;
					}
					// trim endpoint of pattern segment line to line endpoint
					if (tot+pat->pattern[i]*styleFactor > length) {
						cutEndpoint = true;
					}
				}

				if (drop) {
					// do nothing
				}
				else {
					PF_Vector p1 = curP;
					PF_Vector p2 = curP + dp[i];
					
					if (cutStartpoint) {
						p1 = getStartpoint();
					}
					if (cutEndpoint) {
						p2 = getEndpoint();
					}
					
	                painter->drawLine(view->toGui(p1),
                                      view->toGui(p2));
				}
            }
            curP+=dp[i];
            tot+=fabs(pat->pattern[i]*styleFactor);
			//PF_DEBUG->print("pattern. tot: %f", tot);
            done=tot>length;

            i++;
            if (i>=pat->num) {
                i=0;
            }
        } while(!done);

        delete[] dp;

    }
}



/**
 * Dumps the point's data to stdout.
 */
std::ostream& operator << (std::ostream& os, const PF_Line& l) {
    os << " Line: " << l.getData() << "\n";
    return os;
}


